<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/5/31
 * Time: 15:20
 */

namespace app\api\controller\android\v13;


use app\api\model\Approval;
use app\api\model\AuditMaterialsEvaluate;
use app\api\model\Capital;
use app\api\model\Common;
use app\api\model\OrderModel;
use app\api\model\Reimbursement;
use think\Controller;
use think\Db;
use WeCom\WeCom;
use app\api\model\Authority;
use think\Exception;
use app\api\model\AuditMaterials as AuditMaterialsModel;

class AuditMaterials extends Controller
{
    protected $us;
    
    public function _initialize()
    {
        $this->us = Authority::check(1);
        
    }
    
    public function index(AuditMaterialsModel $auditMaterials, Capital $capital, OrderModel $orderModel, AuditMaterialsEvaluate $auditMaterialsEvaluate,Common $common)
    {
        $data       = request()->post();
        $capital_id = json_decode($data['manifestList'], true);
        if (empty($capital_id)) {
            r_date(null, 300, '参数错误');
        }
        $capitalId = array_column($capital_id, 'capitalId');
        $auditMaterials->startTrans();
        $capital->startTrans();
        $auditMaterialsEvaluate->startTrans();
       db()->startTrans();
        try {
            $prove    = json_decode($data['prove'], true);
            $Select   = json_decode($data['checkSelect'], true);
            $supplier = json_decode($data['supplier'], true);
            if (empty($prove)) {
                throw new Exception('请填写凭证');
            }
            if (empty($Select)) {
                throw new Exception('请勾选评价');
            }
            $evaluate = [];


//            foreach ($Select as $k => $item) {
//                foreach ($item['choice'] as $list) {
//                    $evaluate[$k]['type']         = $item['type'];
//                    $evaluate[$k]['evaluate']     = $list['id'];
//                    $evaluate[$k]['materials_id'] = $id;
//                }
//
//            }
            $capitalFind = $capital->QueryOne($capitalId[0]);
            if (!empty($capitalFind['acceptance'])) {
                throw new Exception('当前主材尾款放款审批中，请勿重复操作');
            }
            $evaluateLisy = [];
            foreach ($capitalId as $key => $o) {
                $id = $auditMaterials->add(['prove' => empty($prove) ? '' : serialize($prove),
                    'materials_remarks' => $data['materials_remarks'],
                    'capital_id' => $o, 'user_id' => $this->us['user_id'],
                    'creationtime' => time(),
                    'store_id' => $this->us['store_id']]);
                foreach ($Select as $k => $item) {
                    foreach ($item['choice'] as $list) {
                        $evaluate[] = [
                            'type' => $item['type'],
                            'evaluate' => $list['id'],
                            'materials_id' => $id,
                        ];
                        
                    }
                    
                }
                $evaluateLisy[] = $evaluate;
                $capital->isUpdate(true)->save(['acceptance' => $id, 'capital_id' => $o]);
            }
            $reimbursementId = null;
            if (!empty($evaluateLisy)) {
                $auditMaterialsEvaluate->saveAll($evaluate);
            }
            if (isset($data['agencyOrderId']) && !empty($data['agencyOrderId'])) {
                db('log', config('database.zong'))->insert(['ord_id' => $capitalFind['ordesr_id'], 'type' => 89, 'content' => json_encode($data), 'created_at' => time()]);
                $agency_task = \db('agency_task', config('database.zong'))->join('agency', 'agency.agency_id=agency_task.agency_id', 'left')->join('order', 'order.order_id=agency_task.order_id', 'left')->where('agency_task.agency_order_id', $data['agencyOrderId'])->field('agency_task.*,agency.telephone,order.order_no')->where('agency_task.status','<>',2)->select();
                $result      = array();
                foreach ($agency_task as $k => $v) {
                    $result[$v['agency_id']][] = $v;
                }
                $agency_order_sub           = \db('agency_order_sub')->where('agency_order_id', $data['agencyOrderId'])->select();
                $agency_order_subAttachment = [];
                foreach ($agency_order_sub as $i) {
                    $m = json_decode($i['attachment'], true);
                    if ($m) {
                        foreach ($m as $j) {
                            array_push($agency_order_subAttachment, $j['url']);
                        }
                    }
                    
                    
                }
                $agency_order           = \db('agency_order')->where('id', $data['agencyOrderId'])->find();
                $attachmentZong         = json_decode($agency_order['attachment'], true);
                $attachmentZong = empty($attachmentZong) ? [] : array_column($attachmentZong, 'url');
                $attachment='';
                if(!empty(array_merge($attachmentZong, $agency_order_subAttachment))){
                    $attachment             = serialize(array_merge($attachmentZong, $agency_order_subAttachment));
                }
               
                $total_cost             = array_sum(array_column($agency_task, 'total_cost'));
                $first_reimbursement_id = array_column($agency_order_sub, 'first_reimbursement_id');
                $reimbursement          = \db('reimbursement')->whereIn('id', $first_reimbursement_id)->where('status', 1)->sum('money');
                $money                  = 0;
                $op                     = [
                    'order_id' => $capitalFind['ordesr_id'],
                    'reimbursement_name' => $capitalFind['class_b'] . "等主材尾款请款",
                    'money' => (string)round($total_cost - $reimbursement, 2),
                    'voucher' => $attachment,
                    'created_time' => time(),
                    'user_id' => $this->us['user_id'],
                    'status' => 3,
                    'sp_no' => '',
                    'content' => $data['materials_remarks'],
                    'classification' => 4,
                    'submission_time' => time(),
                    'shopowner_id' => $this->us['user_id'],
                    'capital_id' => implode(",", array_column($agency_task, 'capital_id')),
                    'payment_notes' => '',
                    'secondary_classification' => 17];
                $common->MultimediaResources($capitalFind['ordesr_id'],$this->us['user_id'],array_merge($attachmentZong, $agency_order_subAttachment),12);
                $reimbursementId        = db('reimbursement')->insertGetId($op);
                $reimbursement_agency   = [];
                if ($reimbursementId) {
                    $agency_incre = \db('agency_incre')->where('agency_order_id',$data['agencyOrderId'])->select();
                    if(empty($agency_incre)){
                        foreach ($result as $k => $item) {
                            $reimbursementRelationMoney = db('reimbursement_relation')->join('reimbursement','reimbursement.id=reimbursement_relation.reimbursement_id','left')->where('reimbursement.status', 1)->whereIn('reimbursement_relation.reimbursement_id', $first_reimbursement_id)->where('bank_id', $k)->sum('reimbursement_relation.money');
                            
                            $reimbursement_relation    = db('reimbursement_relation')->insertGetId(['reimbursement_id' => $reimbursementId,
                                'capital_id' => implode(",", array_column($result[$k], 'capital_id')),
                                'bank_id' => $k,
                                'money' => (string)round(array_sum(array_column($result[$k], 'total_cost')) - $reimbursementRelationMoney,2),
                                'receipt_number' => "NO" . time()]);
                            $abnormalSettlementContent = [];
                            foreach ($supplier as $key => $value) {
                                if (isset($value['ckEndMoney']) && $value['ckEndMoney'] == 1) {
                                    $amount      = 0;
                                    $amount_type = 0;
                                    $ckEndMoney  = 0;
                                    if ($value['agencyId'] == $k) {
                                        $abnormalSettlement = $value['abnormalSettlement'];
                                        foreach ($abnormalSettlement as $v) {
                                            if (isset($v['select']) && $v['select'] == 1) {
                                                $abnormalSettlementContent[] = $v;
                                            }
                                        }
                                        if (empty($abnormalSettlementContent)) {
                                            throw new Exception("请选择结算异常原因");
                                        }
                                        
                                        // $amount      = $value['amount'];
                                        $amount_type = $value['amountType'];
                                        if ($amount_type == 0) {
                                            throw new Exception("请选择结算金额调整方式");
                                        }
                                        if (!isset($value['amount']) || $value['amount'] == 0  ) {
                                            throw new Exception("调整金额不能为0");
                                        }
                                        $ckEndMoney             = 1;
                                        $reimbursement_agency[] = [
                                            'reimbursement_relation_id' => $reimbursement_relation,
                                            'attachment' => empty($attachment) ? '' : $attachment,
                                            'abnormal_settlement' => implode(',', array_column($abnormalSettlementContent, 'id')),
                                            'amount' => $value['amount'],
                                            'reimbursement_id' => $reimbursementId,
                                            'amount_type' => $amount_type,
                                            'abnormal_settlement_reason' => empty($ckEndMoney) ? '' : implode(',', array_column($abnormalSettlementContent, 'title')) . "-" . isset($value['abnormalSettlementReason']) ? $value['abnormalSettlementReason'] : '',
                                            'agency_order_id' => $data['agencyOrderId'],
                                            'create_time' => time(),
                                        ];
                                        if ($value['amount'] != 0 && $ckEndMoney == 1 && $amount_type == 1) {
                                            $money += $value['amount'];
                                            db('reimbursement_relation')->where('relation_id', $reimbursement_relation)->setInc('money', $value['amount']);
                                        } elseif ($value['amount'] != 0 && $ckEndMoney == 1 && $amount_type == 2) {
                                            $money -= $value['amount'];
                                            db('reimbursement_relation')->where('relation_id', $reimbursement_relation)->setDec('money', $value['amount']);
                                        }
                                    }
                                 
                                }
                            }
                            
                            
                        }
                    }else{
                        foreach ($result as $k => $item) {
                            $reimbursementRelationMoney = db('reimbursement_relation')->join('reimbursement','reimbursement.id=reimbursement_relation.reimbursement_id','left')->where('reimbursement.status', 1)->whereIn('reimbursement_relation.reimbursement_id', $first_reimbursement_id)->where('bank_id', $k)->sum('reimbursement_relation.money');
                            
                            $reimbursement_relation    = db('reimbursement_relation')->insertGetId(['reimbursement_id' => $reimbursementId,
                                'capital_id' => implode(",", array_column($result[$k], 'capital_id')),
                                'bank_id' => $k,
                                'money' => (string)round(array_sum(array_column($result[$k], 'total_cost')) - $reimbursementRelationMoney,2),
                                'receipt_number' => "NO" . time()]);
                            $abnormalSettlementContent = [];
                            foreach ($supplier as $key => $value) {
                               
                                $incre_type=0;
                                foreach ($value['agencyIncreList']['abnormalSettlement'] as $k2 => $v2) {
                                   if($v2['select']==1){
                                        $incre_type=$v2['id'];
                                    }
                        
                                }
                                $storeUserImg='';
                                if(!empty($value['agencyIncreList']['storeUserImg'])){
                                    foreach ($value['agencyIncreList']['storeUserImg'] as $k3 => $v3) {
                                        $storeUserImgList[$k3]['title']="默认名称";
                                        $storeUserImgList[$k3]['url']=$v3;
                            
                                    }
                                    $storeUserImg=json_encode($storeUserImgList);
                                }
                                $status=2;
                                $store_adjust_money=0;
                                $agency_incre_money=array_sum(array_column($agency_incre,'agency_incre_money'));
                                if($value['agencyIncreList']['status']==0){
                                    throw new Exception("请先确认/修改尾款增减金额");
                                }
                                if(isset($value['agencyIncreList']['moneyType']) && $value['agencyIncreList']['moneyType']==1){
                                    $store_adjust_money=$value['agencyIncreList']['storeUserMoney'];
                                    $status=1;
                                    $agency_incre_money=$store_adjust_money;
                                    $money +=$store_adjust_money;
                                    $titleSms="修改金额为".$store_adjust_money."元"; 
                                }
                                if(isset($value['agencyIncreList']['moneyType']) && $value['agencyIncreList']['moneyType']==2){
                                    $status=2;
                                    $store_adjust_money=0;
                                    $agency_incre_money=0;
                                    $money +=0;
                                    $titleSms="修改为不增加金额";
                                }
                                if(!isset($value['agencyIncreList']['moneyType']) && $value['agencyIncreList']['status']==1){
                                  
                                    $store_adjust_money=0;
                                    $status=1;
                                    $money +=$agency_incre_money;
                                    $titleSms="修改金额为".$agency_incre_money."元";
                                }
                                $agency_incre = [
                                    'incre_type' => $incre_type,
                                    'store_adjust_money'=>$store_adjust_money,
                                    'reject_reason'=>isset($value['agencyIncreList']['storeUserReason'])?$value['agencyIncreList']['storeUserReason']:'',
                                    'status' => $status,
                                    'reject_attachment' => $storeUserImg,
                                    'approval_time' => time(),
                                    'update_time'=>time(),
                                    ];
                            }
                            \db('agency_incre')->where('agency_order_id',$data['agencyOrderId'])->update($agency_incre);
                            $amount_type=2;
                            if($agency_incre_money>0){
                               $amount_type=1;
                            }
                            
                                $reimbursement_agency[] = [
                                    'reimbursement_relation_id' => $reimbursement_relation,
                                    'attachment' => empty($attachment) ? '' : $attachment,
                                    'abnormal_settlement' => $incre_type,
                                    'amount' => $agency_incre_money,
                                    'type'=>2,
                                    'reimbursement_id' => $reimbursementId,
                                    'amount_type' => $amount_type,
                                    'abnormal_settlement_reason' => $value['agencyIncreList']['increType'],
                                    'agency_order_id' => $data['agencyOrderId'],
                                    'create_time' => time(),
                                ];
                            
                            if ($agency_incre_money>0) {
                               
                                db('reimbursement_relation')->where('relation_id', $reimbursement_relation)->setInc('money', $agency_incre_money);
                            } else {
                               
                                db('reimbursement_relation')->where('relation_id', $reimbursement_relation)->setDec('money', $agency_incre_money);
                            }
                            if(!empty($result[$k]) && (isset($value['agencyIncreList']['moneyType']) && ($value['agencyIncreList']['moneyType']==1 || $value['agencyIncreList']['moneyType']==2))){
                                sendMsg($result[$k][0]['telephone'],'477065259',[$result[$k][0]['order_no'],$titleSms]);
                            }
                            
                        }
                    }
                    if (!empty($reimbursement_agency)) {
                        \db('reimbursement_agency')->insertAll($reimbursement_agency);
                    }
                    
                }
                \db('agency_order')->where('id', $data['agencyOrderId'])->update(['last_payment_add_time' => time()]);
//                $completion_time = max(array_column($agency_task, 'app_user_completion_time'));
//                \db('agency_order')->where('id', $data['agencyOrderId'])->where('completion_time', 0)->update(['status' => $completion_time]);
                \db('agency_order_sub')->where('agency_order_id', $data['agencyOrderId'])->update(['last_reimbursement_id' => $reimbursementId]);
                \db('reimbursement')->where('id', $reimbursementId)->setInc('money', $money);
                $reimbursementMoney=\db('reimbursement')->where('reimbursement.status', 1)->where('id', $reimbursementId)->sum('money');
                $reimbursement_relationMoney=\db('reimbursement_relation')->join('reimbursement','reimbursement.id=reimbursement_relation.reimbursement_id','left')->where('reimbursement.status', 1)->whereIn('reimbursement_relation.reimbursement_id', $reimbursementId)->sum('reimbursement_relation.money');
                if($reimbursementMoney <$reimbursement_relationMoney || $reimbursementMoney  != $reimbursement_relationMoney){
                    $WeCom=new WeCom();
                    $WeCom->pushWeChatMessage(json_encode(['title'=>"供应商请款reimbursement_relation的金额不等于reimbursement金额",'reimbursementId'=>$reimbursementId],JSON_UNESCAPED_UNICODE));
                    //throw new Exception("数据异常，请等待2秒重新提交");
                }
            }
           
            $materialScience = new MaterialScience();
            $approval        = new Approval();
            $title           = array_search(4, array_column($materialScience->list_reimbursement_type(2), 'type'));
            $title           = $this->us['username'] . $materialScience->list_reimbursement_type(2)[$title]['name'] . '报销';
            db()->commit();
            $capital->commit();
            $auditMaterials->commit();
            $auditMaterialsEvaluate->commit();
            if (isset($data['agencyOrderId']) && !empty($data['agencyOrderId']) && $reimbursementId) {
                $approval->Reimbursement($reimbursementId, $title, $this->us['username'], 4);
            }
            $totalCapital   = $capital->where(['ordesr_id' => $capitalFind['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();
            $alreadyCapital = $capital->where('acceptance', '<>', 0)->where(['ordesr_id' => $capitalFind['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();
            if ($totalCapital == $alreadyCapital) {
                $orderModel->isUpdate(true)->save(['order_id' => $capitalFind['ordesr_id'], 'acceptance_time' => time()]);
            }
            
            json_decode(sendOrder($capitalFind['ordesr_id']), true);
            r_date([], 200, '操作成功');
        } catch (Exception $e) {
            $auditMaterials->rollback();
            $capital->rollback();
            db()->rollback();
            $auditMaterialsEvaluate->rollback();
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    public
    function materialEvaluate(AuditMaterialsModel $auditMaterials, Reimbursement $reimbursement)
    {
        $data      = request()->get();
        $capitalId = '';
        if (isset($data['capitalId']) && $data['capitalId'] != '') {
            $capitalId = $data['capitalId'];
        }
        $agencylist          = [];
        $agencyIncreList=null;
        $abnormal_settlement = null;
        if (isset($data['agencyOrderId']) && $data['agencyOrderId'] != '') {
            $agency_task = \db('agency_task', config('database.zong'))->join('agency', 'agency.agency_id=agency_task.agency_id', 'left')->where('agency_task.agency_order_id', $data['agencyOrderId'])->field('agency.agency_name,agency_task.agency_id,agency_task.total_cost as totalCost,agency_task.capital_id')->where('agency_task.status','<>',2)->select();
            $resultList  = [];
            foreach ($agency_task as $k => $v) {
                $resultList[$v['agency_id']][] = $v;
            }
            
            $capitalId           = implode(',', array_column($agency_task, 'capital_id'));
            $abnormal_settlement = \db('sys_config', config('database.zong'))->where('statusss', 1)->where('keyss', 'abnormal_settlement')->value('valuess');
            foreach ($resultList as $k => $v) {
                $result['agencyName']         = $v[0]['agency_name'];
                $result['agencyId']           = $k;
                $result['totalCost']          = array_sum(array_column($v, 'totalCost'));
                $result['paid']               = \db('agency_order_sub', config('database.zong'))
                    ->join('reimbursement', 'reimbursement.id=agency_order_sub.first_reimbursement_id', 'left')
                    ->where('agency_order_sub.agency_order_id', $data['agencyOrderId'])
                    ->where('agency_order_sub.agency_id', $k)
                    ->where('reimbursement.status', 1)
                    ->sum('reimbursement.money');
                $result['byAmount']           = $result['totalCost'] - $result['paid'];
                $result['byAmounts']=$result['byAmount'];
                $result['abnormalSettlement'] = empty($abnormal_settlement) ? null : json_decode($abnormal_settlement, true);
                $agency_incre = \db('agency_incre')->where('agency_order_id',$data['agencyOrderId'])->find();
           
                if(!empty($agency_incre)){
                    $agencyIncreList['agencyRemark']=$agency_incre['agency_remark'];//供应商补充说明
                    $agencyIncreList['status']=$agency_incre['status'];//审核状态：0.未审核；1.通过；2.驳回
                    $agencyIncreList['rejectReson']=$agency_incre['reject_reason'];//驳回原因
                    $agencyIncreList['increType']='';//驳回原因
                    $agencyIncreList['moneyType']=1;//驳回原因
                    $agencyIncreMoney=$agency_incre['agency_incre_money'];
                    if($agency_incre['agency_incre_money']> 0 && $agency_incre['store_adjust_money']>0){
                        $agencyIncreMoney=$agency_incre['store_adjust_money'];
                    }
                    $agencyIncreList['agencyIncreMoney']=$agencyIncreMoney;//供应商增加款金额'
                    $result['byAmounts']+=$agencyIncreList['agencyIncreMoney'];
                    $agencyIncreList['storeAdjustMoney']=$agency_incre['store_adjust_money'];//店长调整金额
                    $agencyIncreList['attachment']=empty($agency_incre['attachment']) ? null : array_column(json_decode($agency_incre['attachment'], true),'url');//凭证;//凭证
                    $agencyIncreList['rejectAttachment']=empty($agency_incre['reject_attachment']) ? null : array_column(json_decode($agency_incre['reject_attachment'], true),'url');//凭证
                    $agencyIncreList['abnormalSettlement']=[
                        [
                            'id'=> 1,
                            'title'=> "增项金额",
                            'select'=>0
                        ],
                        [
                            'id'=> 2,
                            'title'=> "配件金额",
                            'select'=>0
                        ],
                        [ 
                            'id'=> 3,
                            'title'=> "运费",
                            'select'=>0
                        ],
                        [
                            'id'=> 4,
                            'title'=> "安装或服务费",
                            'select'=>0
                        ],
                        [
                            'id'=> 5,
                            'title'=> "其他",
                            'select'=>0
                        ],
                    ];
                    foreach ($agencyIncreList['abnormalSettlement'] as $k => $v) {
                        if($v['id']==$agency_incre['incre_type']){
                            $agencyIncreList['abnormalSettlement'][$k]['select']=1;
                            $agencyIncreList['increType']=$v['title'];
                        }
                    }
               $result['agencyIncreList']=$agencyIncreList;
            }
            $agencylist[]                 = $result;
          
            }
           
          
            
        }
        if (empty($capitalId)) {
            r_date(null, 300, '参数错误');
        }
        $description = \db('user_config', config('database.zong'))->where('key', 'audit_materials_evaluate')->value('value');
        $capital     = \db('capital')->whereIn('capital_id', $capitalId)->field('class_b,concat(un_Price,"/",company) as company,square,capital_id as capitalId')->select();
        
        $auditMaterialsList = $auditMaterials->queryFirst($capitalId);
        $description        = json_decode($description, true);
        if (!empty($auditMaterialsList)) {
            $list = $auditMaterialsList->auditEvaluate;
            if (!empty($list)) {
                foreach ($description as $k => $item) {
                    foreach ($item['choice'] as $k1 => $value) {
                        $description[$k]['choice'][$k1]['select'] = 0;
                        foreach ($list as $v) {
                            if ($item['type'] == $v['type'] && $value['id'] == $v['evaluate']) {
                                $description[$k]['choice'][$k1]['select'] = 1;
                            }
                        }
                    }
                    
                }
            }
        }
        r_date(['manifestList' => $capital, 'description' => $description, 'result' => $agencylist, 'prove' => empty($auditMaterialsList->prove) ? null : unserialize($auditMaterialsList->prove), 'materials_remarks' => empty($auditMaterialsList->materials_remarks) ? '' : $auditMaterialsList->materials_remarks], 200, '操作成功');
    }
    
}